<template>
  <div class="mine-container" v-if="userInfo">
    <!-- 个人信息模块 -->
    <div class="profile-module">
      <div class="user-info">
        <img :src="avatarFile ? userInfo.avatar : 'http://localhost:8092' + userInfo.avatar" alt="Avatar" class="user-avatar" />
        <div class="user-details">
          <h2 class="user-name">{{ userInfo.nickname }}</h2>
          <span class="user-number">我的学号: {{ userInfo.number }}</span>
        </div>
      </div>

      <div class="edit-profile">
        <a href="#" @click.prevent="navigateToEditProfile">编辑资料</a>
      </div>

      <div class="user-status">
        <div 
          class="status-item" 
          v-for="(status, index) in statusList" 
          :key="status.name"
          @click="navigateToOrderList(index + 1)"
        >
          <div class="status-count">{{ status.count }}</div>
          <span>{{ status.name }}</span>
        </div>
      </div>
    </div>

    <!-- 交易中心模块 -->
    <div class="transaction-center">
      <div class="tc-header">
        <h2>📦 交易中心</h2>
        <div class="tc-filters">
          <span 
            v-for="filter in filters" 
            :key="filter.value"
            :class="{ active: activeFilter === filter.value }"
            @click="changeFilter(filter.value)"
          >
            {{ filter.label }}
          </span>
        </div>
      </div>
      
      <div class="tc-stats">
        <div 
          class="stat-card"
          v-for="stat in transactionStats"
          :key="stat.type"
          @mouseenter="hoverStat(stat.type)"
          @mouseleave="resetStat"
        >
          <div class="sc-icon" :class="stat.type">
            <component :is="stat.icon" />
          </div>
          <div class="sc-content">
            <div class="sc-count">{{ stat.count }}</div>
            <div class="sc-title">{{ stat.title }}</div>
            <div class="sc-sub">{{ stat.subtitle }}</div>
          </div>
          <div class="sc-actions">
            <el-button 
              v-for="action in stat.actions" 
              :key="action.name"
              :type="action.type"
              size="mini"
              @click.stop="handleAction(action.command)"
            >
              {{ action.name }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 服务推荐模块 -->
    <div class="recommend-module">
      <h2>🔍 推荐服务</h2>
      <div class="rm-grid">
        <div class="service-card" v-for="service in services" :key="service.name">
          <div class="sc-icon" :class="service.type">
            <component :is="service.icon" />
          </div>
          <h3>{{ service.name }}</h3>
          <p>{{ service.desc }}</p>
        </div>
      </div>
    </div>
    <AnalysisBoard 
      v-model:visible="analysisVisible"
      :seller-id="userInfo.userId"
    />
  </div>
    <!-- 编辑资料弹窗 -->
    <el-dialog
    v-model="editDialogVisible"
    title="编辑资料"
    width="500px"
    @closed="handleDialogClose"
  >
    <el-form :model="editForm" label-width="80px">
      <!-- 头像上传 -->
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleAvatarChange"
        >
          <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
          <img v-else-if="userInfo.avatar" :src="avatarFile ? userInfo.avatar : 'http://localhost:8092' + userInfo.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <!-- 其他表单字段 -->
      <el-form-item label="昵称">
        <el-input v-model="editForm.nickname" />
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="editForm.sex" placeholder="请选择">
          <el-option label="男" value="01" />
          <el-option label="女" value="02" />
        </el-select>
      </el-form-item>

      <el-form-item label="专业">
        <el-input v-model="editForm.major" />
      </el-form-item>

      <el-form-item label="电话">
        <el-input v-model="editForm.phone" />
      </el-form-item>

      <el-form-item label="邮箱">
        <el-input v-model="editForm.email" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 已售出订单弹窗 -->
  <el-dialog
    v-model="soldOrdersVisible"
    title="已售出订单"
    width="80%"
    top="5vh"
  >
    <el-table :data="soldOrders" border stripe  :fit="false"
  lazy>
      <el-table-column prop="orderNumber" label="订单号" width="200" />
      <el-table-column prop="productName" label="商品名称" />
      <el-table-column label="金额" width="120">
        <template #default="{row}">
          ¥{{ row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="statusTagType(row.status)">
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{row}">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  <!-- 已购入订单弹窗 -->
<el-dialog
  v-model="purchasedOrdersVisible"
  title="已购入订单"
  width="80%"
  top="5vh"
>
  <el-table :data="purchasedOrders" border stripe
   :fit="false"
  lazy>
    <el-table-column prop="orderNumber" label="订单号" width="200" />
    <el-table-column prop="productName" label="商品名称" />
    <el-table-column label="金额" width="120">
      <template #default="{row}">
        ¥{{ row.totalAmount }}
      </template>
    </el-table-column>
    <el-table-column label="订单状态" width="120">
      <template #default="{row}">
        <el-tag :type="statusTagType(row.status)">
          {{ formatStatus(row.status) }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="createdAt" label="创建时间" width="180">
      <template #default="{row}">
        {{ formatDate(row.createdAt) }}
      </template>
    </el-table-column>
  </el-table>
</el-dialog>
</template>


<script>
import axios from 'axios';
import { defineComponent } from 'vue';
import { 
  Document,
  Box,
  ShoppingCart,
  Coin,
  Timer,
  Setting,
  TrendCharts,
  Goods
} from '@element-plus/icons-vue';
import AnalysisBoard from '@/components/components/AnalysisBoard.vue'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElUpload,
  ElButton,
} from 'element-plus';
export default {
  name: 'Mine',
  components: {
    Document,
    Box,
    ShoppingCart,
    Coin,
    Timer,
    Setting,
    TrendCharts,
    Goods,
    AnalysisBoard,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElUpload,
    ElButton,
  },
  data() {
    return {
       soldOrdersVisible: false,
       soldOrders: [],
      analysisVisible: false,
      purchasedOrdersVisible: false, // 已购入订单弹窗显示状态
    purchasedOrders: [],            // 已购入订单数据
      userInfo: null,
      statusList: [
        { name: '待付款', count: 0 },    // 对应状态1
        { name: '待发货', count: 0 },    // 对应状态2
        { name: '待收货', count: 0 },    // 对应状态3
        { name: '待评价', count: 0 },    // 对应状态4
        { name: '售后', count: 0 }       // 对应状态5
      ],
      activeFilter: 'all',
      filters: [
        { label: '全部交易', value: 'all' },
        { label: '最近一周', value: 'week' },
        { label: '本月', value: 'month' }
      ],
      transactionStats: [
        {
          type: 'publish',
          title: '我的发布',
          subtitle: '当前在线商品',
          count: 0,
          icon: 'Document',
          actions: [
            { name: '管理', type: 'primary', command: 'manage' },
            { name: '分析', type: 'info', command: 'analyze' }
          ]
        },
        {
          type: 'sold',
          title: '已售出',
          subtitle: '累计交易成功',
          count: 0,
          icon: 'ShoppingCart',
          actions: [
            { name: '查看', type: 'success', command: 'view' },
            { name: '导出', type: 'warning', command: 'export' }
          ]
        },
        {
          type: 'purchased',
          title: '已购入',
          subtitle: '消费记录',
          count: 0,
          icon: 'Goods',
          actions: [
            { name: '明细', type: 'primary', command: 'detail' },
            { name: '导出', type: 'danger', command: 'review' }
          ]
        }
      ],
      services: [
        {
          name: '交易分析',
          desc: '查看详细交易数据报表',
          type: 'analytics',
          icon: 'TrendCharts'
        },
        {
          name: '快捷发布',
          desc: '快速发布新商品',
          type: 'publish',
          icon: 'Coin'
        },
        {
          name: '售后服务',
          desc: '处理退换货请求',
          type: 'service',
          icon: 'Setting'
        }
      ],
      editDialogVisible: false,
    editForm: {
      nickname: '',
      sex: '',
      major: '',
      phone: '',
      email: '',
    },
    avatarFile: null,
    avatarPreview: '',
    };
  },
  mounted() {
    this.fetchUserDetails();
  },
  methods: {
     formatDate(timestamp) {
        return new Date(timestamp).toLocaleString();
      },
      formatStatus(status) {
        const statusMap = {
          1: '待付款',
          2: '已付款',
          3: '已发货', 
          4: '已完成',
          5: '已取消'
        };
        return statusMap[status] || '未知状态';
      },
      statusTagType(status) {
        const typeMap = {
          1: 'warning',
          2: 'primary',
          3: 'success',
          4: 'info',
          5: 'danger'
        };
        return typeMap[status] || 'info';
      },
    
    async fetchPublishedCount(userId) {
      try {
        const response = await axios.get(
          'http://localhost:8092/product/getPublishedProductQuantityById',
          { params: { userId } }
        );
        
        if (response.data.code === 200) {
          const publishStat = this.transactionStats.find(
            item => item.type === 'publish'
          );
          if (publishStat) {
            publishStat.count = response.data.data;
          }
        }
      } catch (error) {
        console.error('获取发布数量失败:', error);
        this.$message.error('获取发布数据失败');
      }
    },
    async fetchPurchasedCount(userId) {
    try {
      const response = await axios.get(
        'http://localhost:8092/order/soldOutByuserId', 
        { params: { userId } }
      );
      
      if (response.data.code === 200) {
        // 更新已购入数量
        const purchasedStat = this.transactionStats.find(
          item => item.type === 'purchased'
        );
        if (purchasedStat) {
          purchasedStat.count = response.data.data;
        }
      }
    } catch (error) {
      console.error('获取已购数量失败:', error);
    }
  },
  async fetchSoldCount(userId) {
      try {
        const response = await axios.get(
          'http://localhost:8092/user/getSoldOut',
          { params: { userId } }
        );
        
        if (response.data.code === 200) {
          const soldStat = this.transactionStats.find(
            item => item.type === 'sold'
          );
          if (soldStat) {
            soldStat.count = response.data.data;
          }
        }
      } catch (error) {
        console.error('获取已售出数量失败:', error);
        // 可选：显示错误提示
        this.$message.error('获取销售数据失败');
      }
    },
    async fetchUserDetails() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          console.error('No token found');
          return;
        }

        const response = await axios.get('http://localhost:8092/user/getUserDetails', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (response.data.code === 200) {
          this.userInfo = response.data.data;
          if (this.userInfo.userId) {
            await Promise.all([
            this.fetchOrders(this.userInfo.userId),
            this.fetchPurchasedCount(this.userInfo.userId) ,// 新增调用
            this.fetchSoldCount(this.userInfo.userId) ,
            this.fetchPublishedCount(this.userInfo.userId) 
          ]);
          }
        } else {
          console.error('Failed to fetch user details:', response.data.message);
        }
      } catch (error) {
        console.error('Error fetching user details:', error);
      }
    },

    async fetchOrders(userId) {
      try {
        const response = await axios.get('http://localhost:8092/order/getOrderDetailByUserId', {
          params: { userId: userId }
        });

        if (response.data.code === 200 && response.data.data) {
          this.processOrders(response.data.data);
        }
      } catch (error) {
        console.error('获取订单失败:', error);
      }
    },

    processOrders(orders) {
      this.statusList = this.statusList.map(status => ({ ...status, count: 0 }));
      orders.forEach(order => {
        const statusIndex = order.status - 1;
        if (statusIndex >= 0 && statusIndex < this.statusList.length) {
          this.statusList[statusIndex].count++;
        }
      });
    },

    navigateToEditProfile() {
    this.editForm = {
      nickname: this.userInfo.nickname,
      sex: this.userInfo.sex,
      major: this.userInfo.major,
      phone: this.userInfo.phone,
      email: this.userInfo.email,
    };
    this.avatarPreview = '';
    this.avatarFile = null;
    this.editDialogVisible = true;
  },
  handleAvatarChange(file) {
    const isImage = file.raw.type.startsWith('image/');
    const isLt2M = file.raw.size / 1024 / 1024 < 2;

    if (!isImage) {
      this.$message.error('只能上传图片文件');
      return false;
    }
    if (!isLt2M) {
      this.$message.error('图片大小不能超过2MB');
      return false;
    }

    this.avatarFile = file.raw;
    this.avatarPreview = URL.createObjectURL(file.raw);
    return false;
  },
  async submitEditForm() {
    const formData = new FormData();
    formData.append('userId', this.userInfo.userId);
    formData.append('nickname', this.editForm.nickname);
    formData.append('sex', this.editForm.sex);
    formData.append('major', this.editForm.major);
    formData.append('phone', this.editForm.phone);
    formData.append('email', this.editForm.email);
    if (this.avatarFile) {
      formData.append('avatar', this.avatarFile);
    }

    try {
      const token = localStorage.getItem('token');
      const response = await axios.post('http://localhost:8092/user/updateUser', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${token}`
        }
      });

      if (response.data.code === 200) {
        this.$message.success('资料更新成功');
        this.editDialogVisible = false;
        await this.fetchUserDetails();
      } else {
        this.$message.error('更新失败');
      }
    } catch (error) {
      this.$message.error('更新失败');
    }
  },

  handleDialogClose() {
    this.avatarPreview = '';
    this.avatarFile = null;
  },
    navigateToOrderList(status) {
      if (!this.userInfo?.userId) {
        console.error('用户ID不存在');
        return;
      }
      
      const routeData = this.$router.resolve({
        path: '/orders',
        query: {
          status: status,
          userId: this.userInfo.userId
        }
      });
      window.open(routeData.href, '_blank');
    },
    changeFilter(filter) {
      this.activeFilter = filter;
      console.log(`切换筛选条件: ${filter}`);
    },

    hoverStat(type) {
      console.log(`悬停统计卡片: ${type}`);
    },

    resetStat() {
      console.log('取消悬停状态');
    },

    handleAction(command) {
      const actions = {
        manage: () => {
      if (!this.userInfo?.userId) {
        this.$message.error('用户信息获取失败');
        return;
      }
      const route = this.$router.resolve({
        path: '/productmanage',
        query: { userId: this.userInfo.userId }
      });
      window.open(route.href, '_blank');
    },
    analyze: () => {
        this.analysisVisible = true,
        console.log('分析数据')
      },
       view: async () => {
          try {
            if (!this.userInfo?.userId) {
              this.$message.error('用户信息获取失败');
              return;
            }
            
            const res = await axios.get('http://localhost:8092/order/getOrderBySellerId', {
              params: { sellerId: this.userInfo.userId }
            });
            
            if (res.data.code === 200) {
              this.soldOrders = res.data.data;
              this.soldOrdersVisible = true;
            } else {
              this.$message.error('获取订单失败');
            }
          } catch (error) {
            this.$message.error('请求失败');
            console.error(error);
          }
        },
       export: () => this.exportData(),
       detail: async () => {
      try {
        if (!this.userInfo?.userId) {
          this.$message.error('用户信息获取失败');
          return;
        }
        
        const res = await axios.get('http://localhost:8092/order/getOrderDetailByUserId', {
          params: { userId: this.userInfo.userId }
        });
        
        if (res.data.code === 200) {
          this.purchasedOrders = res.data.data;
          this.purchasedOrdersVisible = true;
        } else {
          this.$message.error('获取订单失败');
        }
      } catch (error) {
        this.$message.error('请求失败');
        console.error(error);
      }
    },
        review: () => console.log('进行商品评价')
      };
      actions[command]?.();
    },
    // 在methods中添加这个方法
async fetchSoldOrders() {
  try {
    if (!this.userInfo?.userId) {
      this.$message.error('用户信息获取失败');
      return false;
    }
    
    const res = await axios.get('http://localhost:8092/order/getOrderBySellerId', {
      params: { sellerId: this.userInfo.userId }
    });
    
    if (res.data.code === 200) {
      this.soldOrders = res.data.data;
      return true;
    }
    this.$message.error('获取订单失败');
    return false;
  } catch (error) {
    this.$message.error('请求失败');
    console.error(error);
    return false;
  }
},
    async exportData() {
   const success = await this.fetchSoldOrders();
  
  if (!success || this.soldOrders.length === 0) {
    this.$message.warning('没有可导出的数据');
    return;
  }

    // 处理数据为CSV格式
    const csvContent = this.generateCSV();
    
    // 创建Blob对象
    const blob = new Blob([`\uFEFF${csvContent}`], { 
      type: 'text/csv;charset=utf-8;' 
    });
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.href = url;
    link.download = `已售出订单_${new Date().toLocaleDateString()}.csv`;
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  },

  generateCSV() {
    const headers = ['订单号', '商品名称', '金额', '状态', '创建时间'];
    const rows = this.soldOrders.map(order => [
      `"${order.orderNumber}"`,
      `"${order.productName}"`,
      order.totalAmount,
      `"${this.formatStatus(order.status)}"`,
      `"${this.formatDate(order.createdAt)}"`
    ]);

    return [headers.join(',')]
      .concat(rows.map(row => row.join(',')))
      .join('\n');
  },
  }

  }
</script>

<style scoped>
.mine-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  margin: 0;
  padding: 20px;
}

.profile-module {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: start;
  margin-bottom: 10px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 15px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  margin: 0;
  font-size: 24px;
}

.user-number {
  color: #888;
  font-size: 16px;
  margin-top: 5px;
}

.edit-profile {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.edit-profile a {
  color: #3498db;
  text-decoration: none;
  font-size: 16px;
  cursor: pointer;
}

.user-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
  text-align: center;
  position: relative;
  cursor: pointer;
  transition: background-color 0.3s;
  padding: 8px 0;
}

.status-item:hover {
  background-color: #f8f9fa;
}

.status-item:not(:last-child)::after {
  content: "";
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 2px;
  height: 20px;
  background-color: #ccc;
}

.status-count {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.status-item span {
  font-size: 18px;
  font-weight: bold;
}

.another-module {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* 交易中心样式 */
.transaction-center {
  background: #ffffff;
  border-radius: 16px;
  padding: 28px;
  margin: 20px 0;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
}

.tc-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 28px;
}

.tc-header h2 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0;
}

.tc-filters span {
  margin-left: 25px;
  padding: 8px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #7f8c8d;
}

.tc-filters span:hover,
.tc-filters .active {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.tc-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.stat-card {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(79, 114, 205, 0.15);
}

.sc-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}

.sc-icon.publish { background: rgba(64, 158, 255, 0.1); color: #409EFF; }
.sc-icon.sold { background: rgba(103, 194, 58, 0.1); color: #67C23A; }
.sc-icon.purchased { background: rgba(255, 153, 0, 0.1); color: #FF9900; }

.sc-count {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.sc-title {
  font-size: 16px;
  color: #34495e;
  margin-bottom: 4px;
}

.sc-sub {
  font-size: 12px;
  color: #7f8c8d;
}

.sc-actions {
  margin-top: 16px;
  display: flex;
  gap: 8px;
}

/* 推荐服务样式 */
.recommend-module {
  background: white;
  border-radius: 16px;
  padding: 28px;
  margin-top: 20px;
}

.rm-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  margin-top: 20px;
}

.service-card {
  padding: 24px;
  border-radius: 12px;
  background: #f8fafc;
  transition: all 0.3s ease;
}

.service-card:hover {
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.service-card h3 {
  color: #2c3e50;
  margin: 16px 0 8px;
}

.service-card p {
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.5;
}

.service-card .sc-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}
/* 保证弹窗层级正确 */
.el-dialog__wrapper {
  z-index: 2000 !important;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
.el-table {
  margin-top: 20px;
}

:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>